/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.spring.cloud;

import com.google.common.collect.Lists;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;

import java.util.List;
import java.util.concurrent.CompletionStage;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @author william
 * @since 2024/4/7
 */
public class AutoIncreaseIDGenerator implements GUIDGenerator {
    private final RedissonClient redissonClient;

    public AutoIncreaseIDGenerator(@Nonnull RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Nonnull
    @Override
    public String acquireOne(@Nullable String specification) {
        long updatedLong = this.getUpdatedLongFromRedisson(specification).incrementAndGet();
        return this.fillGUID(specification, updatedLong);
    }

    @Nonnull
    @Override
    public List<String> acquireMany(@Nullable String specification, int size) {
        long end = this.getUpdatedLongFromRedisson(specification).addAndGet(size);
        return this.getManyIfAvailable(specification, end, size);
    }

    @Nonnull
    @Override
    public CompletionStage<String> acquireOneAsync(@Nullable String specification) {
        return this
                .getUpdatedLongFromRedisson(specification)
                .incrementAndGetAsync()
                .thenApplyAsync(updatedLong -> this.fillGUID(specification, updatedLong));
    }

    @Nonnull
    @Override
    public CompletionStage<List<String>> acquireManyAsync(@Nullable String specification, int size) {
        return this.getUpdatedLongFromRedisson(specification)
                .addAndGetAsync(size)
                .thenApplyAsync(end -> this.getManyIfAvailable(specification, end, size));
    }

    private RAtomicLong getUpdatedLongFromRedisson(String specification) {
        String redisNamespace = this.determineNamespace(specification);
        return this.redissonClient.getAtomicLong(redisNamespace);
    }

    private List<String> getManyIfAvailable(String specification, long end, int size) {
        List<String> many = Lists.newArrayList();
        for (int idx = size - 1; idx >= 0; idx--) {
            many.add(this.fillGUID(specification, end - idx));
        }
        return many;
    }
}